﻿using JYH.Business;
using JYH.Framework;
using JYH.Model.API;
using JYH.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Security;
using Microsoft.AspNetCore.Cors;
using JYH.Data;
using System.Text.RegularExpressions;

namespace JYH.Web.MES.Controllers
{
    [EnableCors("AllowAll")] // 应用于整个控制器
    public class PDAController : ApiController
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult Login([FromBody] dynamic info)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysUserInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                SysUserInfo obj = new SysUserInfo();

                obj.UserNO = info.UserNO;
                obj.Pwd = info.Pwd;
                SysUserInfoBLL bLL = new SysUserInfoBLL();

                SysUserInfo user = bLL.Login(obj, out Msg);

                if (user != null)
                {
                    json.Items.Add(user);
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            return Ok(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 获取PDA菜单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult GetPDAMenu([FromBody] dynamic info)
        {
            ResponseJson<MenuModule> json = new ResponseJson<MenuModule>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<MenuModule>();
            string Msg = string.Empty;
            if ((info == null))
            {
                json.Code = 500;
                json.Message = "参数格式错误";
                var res = Request.CreateResponse(HttpStatusCode.OK, json);
                res.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            try
            {
                SysUserInfo LoginUser = JsonConvert.DeserializeObject<SysUserInfo>(JsonConvert.SerializeObject(info));
                SysMenuInfoBLL bLL = new SysMenuInfoBLL();
                List<SysMenuInfo> Menus = new List<SysMenuInfo>();
                Menus = bLL.GetMenu(LoginUser.UserNO, "1", out Msg);

                if (Menus != null)
                {
                    List<SysMenuInfo> PMenus = Menus.FindAll(p => string.IsNullOrEmpty(p.UpMenuID) == true);
                    for (int i = 0; i < PMenus.Count; i++)
                    {
                        MenuModule mm = new MenuModule();
                        mm.ModuleName = PMenus[i].MenuName;
                        for (int j = 0; j < Menus.Count; j++)
                        {
                            if (Menus[j].UpMenuID == PMenus[i].MenuID)
                            {
                                mm.Menus.Add(Menus[j]);
                            }
                        }
                        json.Items.Add(mm);
                    }
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;

                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<MenuModule>();

                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetWarehouseInfo()
        {
            ResponseJson<BasWarehouseInfo> json = new ResponseJson<BasWarehouseInfo>();
            json.Items = new List<BasWarehouseInfo>();
            string Msg = string.Empty;
            try
            {
                BasWarehouseInfoBLL bLL = new BasWarehouseInfoBLL();
                json.Items = bLL.NotPagedQuery(new Sql().Append("Where 1=1"), out Msg, " BasWarehouseInfo.WarehouseNO");
                if (!json.Items.Any())
                {
                    json.Code = 500;
                    return Content(HttpStatusCode.InternalServerError, "暂无数据");
                }
                BasWarehouseInfo info = new BasWarehouseInfo();
                info.WarehouseNO = "";
                info.WarehouseName = "ALL Warehouse";
                json.Items.Insert(0, info);
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 物料上架（无单）
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult PutOnMaterialBarcode([FromBody] WmsStockBarcode Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL bLL = new WmsStockBarcodeBLL();
                bool res = bLL.PutOnMaterialBarcode(ref Info, ref json);
                if (!res)
                {
                    json.Code = 500;
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items.Add(Info);
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        ///  调拨上架
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult TradePutOnBarcode_5([FromBody] WmsTradebarcode Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>();
            json.Items = new List<WmsTradebarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL bLL = new WmsStockBarcodeBLL();
                bool res = bLL.TradePutOnBarcode_5(ref Info, ref json);
                if (!res)
                {
                    json.Code = 500;
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 物料单个扫码下架  无单
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult OutFistMaterialBarcode([FromBody] WmsStockBarcode Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL bLL = new WmsStockBarcodeBLL();

                if (bLL.GetStockBarCodeInfo(null, ref json, "", "", Info.BarcodeNO))
                {
                    List<WmsStockBarcode> lis = new List<WmsStockBarcode>();
                    lis.Add(Info);
                    bool res = bLL.OutMaterialBarcode(ref lis, true, ref json);
                    if (!res)
                    {
                        return Content(HttpStatusCode.InternalServerError, json.Message);
                    }
                }
                else
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items = new List<WmsStockBarcode>();
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 物料批量下架  无单
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult OutMaterialBarcode([FromBody] List<WmsStockBarcode> Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL bLL = new WmsStockBarcodeBLL();
                bool res = bLL.OutMaterialBarcode(ref Info, true, ref json);
                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 条码扫描检索物料
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult QueryMaterialInfo([FromBody] BasBarcodeInfo Info)
        {
            ResponseJson<BasBarcodeInfo> json = new ResponseJson<BasBarcodeInfo>();
            json.Items = new List<BasBarcodeInfo>();
            string Msg = string.Empty;
            try
            {
                BasBarcodeInfoBLL barcodeInfoBLL = new BasBarcodeInfoBLL();
                json.Items.Add(barcodeInfoBLL.GetSingeModel(new Sql().Append($"where BasBarcodeInfo.BarcodeNO='{Info.BarcodeNO}'")));
                if (!json.Items.Any())
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), Info.BarcodeNO);
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 捡料下架--获取未扫描的库存条码
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetStockList([FromBody] BasBarcodeInfo Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                var res = barcodeInfoBLL.GetStockBarCodeInfo(Info, ref json);
                if (!res)
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), Info.BarcodeNO);
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 单据捡料
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetCalculateInfo([FromBody] WmsTradeSource Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>();
            json.Items = new List<WmsTradebarcode>();

            string Msg = string.Empty;
            var res = false;
            try
            {
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();

                switch (Info.TradeType)
                {
                    case 3:
                        List<WmsTradebarcode> barcodes = new List<WmsTradebarcode>();
                        //生产领料单捡料（单项次）
                        res = WmsProductionPickingOrderBLL.TradeOrderPickBarcode(Info.TradeSourceID, Info.CreateUser, out Msg, out barcodes);

                        Sql sql = new Sql();
                        json.Items = barcodes;
                        json.Message = Msg;
                        break;

                    case 5:
                        res = barcodeInfoBLL.GetCalculateInfo(Info, ref json);
                        break;

                    default:
                        res = barcodeInfoBLL.GetCalculateInfo(Info, ref json);
                        break;
                }

                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 库存条码检索
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetStockCodeList([FromBody] BasBarcodeInfo Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                var res = barcodeInfoBLL.GetStockCodeList(Info, ref json);
                if (!res)
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), Info.BarcodeNO);
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 捡料下架--库存集合亮灯
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult QueryLigthInfo([FromBody] LigthList<WmsStockBarcode> Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                barcodeInfoBLL.QueryLigthInfo(Info, ref json);
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        ///  无单 全部下架 （AllDown）
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult AllOffLigthInfo([FromBody] LigthList<WmsStockBarcode> Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                List<WmsStockBarcode> lists = new List<WmsStockBarcode>();
                lists = Info.Items;
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                bool res = barcodeInfoBLL.OutMaterialBarcode(ref lists, Info.LigthCheck, ref json);
                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items = new List<WmsStockBarcode>();
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        ///   单据下架 （AllDown）假下架
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult AllCodeLigthInfo([FromBody] LigthList<WmsStockBarcode> Info)
        {
            ResponseJson<WmsStockBarcode> json = new ResponseJson<WmsStockBarcode>();
            json.Items = new List<WmsStockBarcode>();
            string Msg = string.Empty;
            try
            {
                List<WmsStockBarcode> lists = new List<WmsStockBarcode>();
                lists = Info.Items;
                bool res = false;
                switch (Info.TradeType)
                {
                    default:

                        WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                        res = barcodeInfoBLL.DBMaterialBarcode(ref lists, Info.LigthCheck, Info.OrderNO, ref json);
                        if (!res)
                        {
                            return Content(HttpStatusCode.InternalServerError, json.Message);
                        }
                        json.Items = new List<WmsStockBarcode>();
                        break;

                    case "3":

                        if (string.IsNullOrEmpty(Info.TradeSourceID))
                        {
                            res = WmsProductionPickingOrderBLL.DBMaterialBarcode(ref lists, Info.OrderNO, Info.UserName, ref json);
                        }
                        else
                        {
                            res = WmsProductionPickingOrderBLL.DBMaterialBarcode(ref lists, Info.OrderNO, Info.TradeSourceID, Info.UserName, ref json);
                        }
              
                        if (!res)
                        {
                            return Content(HttpStatusCode.InternalServerError, json.Message);
                        }
                        json.Items = new List<WmsStockBarcode>();
                        break;
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        ///   备料发料下架 （AllDown）真下架
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult AllMPCodeLigthInfo([FromBody] LigthList<WmsTradebarcode> Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>();
            json.Items = new List<WmsTradebarcode>();
            string Msg = string.Empty;
            try
            {
                List<WmsTradebarcode> lists = new List<WmsTradebarcode>();
                lists = Info.Items;
                WmsStockBarcodeBLL barcodeInfoBLL = new WmsStockBarcodeBLL();
                bool res = barcodeInfoBLL.MPMaterialBarcode(ref lists, Info.LigthCheck, Info.OrderNO, ref json);
                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items = new List<WmsTradebarcode>();
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        ///   备料发料确认 （AllDown）
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetStationCode([FromBody] LigthList<WmsTradebarcode> Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>();
            json.Items = new List<WmsTradebarcode>();
            string Msg = string.Empty;
            try
            {
                List<WmsTradebarcode> lists = new List<WmsTradebarcode>();
                lists = Info.Items;
                WmsTradebarcodeBLL barcodeInfoBLL = new WmsTradebarcodeBLL();
                bool res = barcodeInfoBLL.GetStationCode(ref lists, ref json);
                if (!res)
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }
                json.Items = new List<WmsTradebarcode>();
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 单据检索 0 收料入库单   2 收料退库单  3 生产领料单   4 生产退料单  5 物料调拨单   6 其他领料单   7 其他入库单   8 生产缴库单
        ///  9 生产退库单   10 销售出库单  11销售退库单    12盘盈盘库单
        /// </summary>
        /// <param name="Info">数据对象</param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetTradeInfo([FromBody] WmsTradeOrderInfo Info)
        {
            ResponseJson<WmsTradeOrderInfo> json = new ResponseJson<WmsTradeOrderInfo>()
            {
                Code = 200,
                Message = string.Empty,
                Items = new List<WmsTradeOrderInfo>()
            };
            string Msg = string.Empty;
            long total = 0;
            try
            {
                WmsTradeOrderInfoBLL OrderInfoBLL = new WmsTradeOrderInfoBLL();
                Sql sql = new Sql();
                //sql.Append(OrderInfoBLL.SqlSelect);
                switch (Info.TradeType)
                {
                    case 3:
                        {
                            sql.Append(OrderInfoBLL.MFGSqlSelect);
                            sql.Append($"Where WmsTradeOrderInfo.TradeType={Info.TradeType}");

                            break;
                        }
                    case 5:
                        {
                            sql.Append(OrderInfoBLL.DbSqlSelect);
                            sql.Append($"Where WmsTradeOrderInfo.TradeType={Info.TradeType}");

                            break;
                        }
                    case 13:
                        {
                            sql.Append(OrderInfoBLL.MPSqlSelect);
                            sql.Append($"Where WmsTradeOrderInfo.TradeType={Info.TradeType}");

                            break;
                        }
                    default:
                        break;
                }
                if (!string.IsNullOrWhiteSpace(Info.RState))
                {
                    sql.Append($"Where WmsTradeOrderInfo.RState='{Info.RState}'");
                }
                if (string.IsNullOrEmpty(Info.TradeOrderNO) && string.IsNullOrEmpty(Info.CreateTime))
                {
                    sql.Append($"Where WmsTradeOrderInfo.CreateTime>='{DateTime.Today.AddDays(-30).ToString("yyyy-MM-dd")}'");
                }
                else
                {
                    if (!string.IsNullOrEmpty(Info.TradeOrderNO))
                        sql.Append($"Where WmsTradeOrderInfo.TradeOrderNO like '%{Info.TradeOrderNO}%'");
                    if (!string.IsNullOrEmpty(Info.CreateTime))
                        sql.Append($"Where WmsTradeOrderInfo.CreateTime='{Info.CreateTime}'");
                }
                //var list = OrderInfoBLL.PagedQuery(Info.PageIndex, Info.PageSize, sql, out total, out Msg, " WmsTradeOrderInfo.CreateTime desc");
                var list = OrderInfoBLL.PagedQuery(sql, Info.PageIndex, Info.PageSize, out total, out Msg, " WmsTradeOrderInfo.CreateTime desc");
                json.Items = list;
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        /// 单据 物料明细检索
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetTradeInfo_ItemInfo([FromBody] WmsTradeOrderInfo Info)
        {
            ResponseJson<WmsTradeSource> json = new ResponseJson<WmsTradeSource>()
            {
                Items = new List<WmsTradeSource>()
            };
            string Msg = string.Empty;
            try
            {
                WmsTradeSourceBLL OrderInfoBLL = new WmsTradeSourceBLL();
                Sql sql = new Sql();
                sql.Append($"Where WmsTradeOrderInfo.TradeOrderNO='{Info.TradeOrderNO}'");
                var list = OrderInfoBLL.NotPagedQuery(sql, out Msg, "WmsTradeOrderInfo.TradeOrderNO,CONVERT(INT, isnull( WmsTradeSource.ErpItem,0))");
                if (list.Any())
                {
                    json.Items = list.Where(x => x.LackQty > 0).ToList();
                }

                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        /// 获取交易条码信息（单据）
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetTradeInBarCode([FromBody] WmsTradebarcode Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>()
            {
                Items = new List<WmsTradebarcode>()
            };
            string Msg = string.Empty;
            try
            {
                WmsTradebarcodeBLL OrderInfoBLL = new WmsTradebarcodeBLL();
                Sql sql = new Sql();
                switch (Info.RType)
                {
                    //调拨单
                    case "5":
                        sql.Append(OrderInfoBLL.DPSelect);
                        break;

                    default:
                        sql.Append(OrderInfoBLL.SqlSelect);
                        break;
                }
                sql.Append($"Where WmsTradeOrderInfo.TradeOrderNO='{Info.TradeOrderNO}'");

                //状态
                if (Info.RState != "-1")
                {
                    if (Convert.ToInt32(Info.RState) >= 2)
                    {
                        sql.Append($"Where  WmsTradebarcode.RState>=2");
                    }
                    else
                    {
                        sql.Append($"Where  WmsTradebarcode.RState='{Info.RState}'");
                    }
                }
                if (!string.IsNullOrEmpty(Info.MaterialNO))
                {
                    sql.Append($"Where  BasMaterialInfo.MaterialNO='{Info.MaterialNO}'");
                }
                if (!string.IsNullOrEmpty(Info.TradeSourceID))
                {
                    sql.Where("WmsTradebarcode.TradeSouceID='" + Info.TradeSourceID + "'");
                }
                sql.OrderBy("WmsTradebarcode.RState,BasBarcodeInfo.BarcodeNO");
                //return Ok(JsonConvert.SerializeObject(OrderInfoBLL.NotPagedQuery(sql, out Msg, "WmsTradebarcode.BarcodeNO")));
                var list = OrderInfoBLL.myDataBase.Fetch<WmsTradebarcode>(sql);
                if (list.Any())
                {
                    json.Items = list;
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        ///  调拨发料 撤销已扫描的条码信息（单据）
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult DeleteTradeInBarCode([FromBody] WmsTradebarcode Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>()
            {
                Items = new List<WmsTradebarcode>()
            };
            string Msg = string.Empty;
            try
            {
                WmsTradebarcodeBLL OrderInfoBLL = new WmsTradebarcodeBLL();

                if (!OrderInfoBLL.DeleteTradeInBarCode(Info, ref json))
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }

                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        ///  调拨上架撤销
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult DeleteCode_5([FromBody] WmsTradebarcode Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>()
            {
                Items = new List<WmsTradebarcode>()
            };
            string Msg = string.Empty;
            try
            {
                WmsTradebarcodeBLL OrderInfoBLL = new WmsTradebarcodeBLL();

                if (!OrderInfoBLL.DeleteCode_5(Info, ref json))
                {
                    return Content(HttpStatusCode.InternalServerError, json.Message);
                }

                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        ///  批量调拨确认
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult AllComFirm([FromBody] LigthList<WmsTradebarcode> Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>()
            {
                Items = new List<WmsTradebarcode>()
            };
            string Msg = string.Empty;
            try
            {
                string Codes = "'',";
                foreach (var item in Info.Items)
                {
                    Codes += "'" + item.BarcodeNO + "',";
                }
                Codes = Codes.Substring(0, Codes.Length - 1);
                WmsTradebarcodeBLL OrderInfoBLL = new WmsTradebarcodeBLL();
                Sql sql = new Sql();
                sql.Append(OrderInfoBLL.SqlSelect);
                sql.Append($"Where WmsTradeOrderInfo.TradeOrderNO='{Info.OrderNO}'");
                sql.Append($"Where WmsTradebarcode.RState=1 And BasBarcodeInfo.BarcodeNO in ({Codes})");
                sql.OrderBy($"BasBarcodeInfo.BarcodeNO");
                //return Ok(JsonConvert.SerializeObject(OrderInfoBLL.NotPagedQuery(sql, out Msg, "WmsTradebarcode.BarcodeNO")));
                var list = OrderInfoBLL.myDataBase.Fetch<WmsTradebarcode>(sql);
                if (list.Any())
                {
                    json.Items = list;
                    Codes = "";
                    foreach (var item in list)
                    {
                        Codes += "'" + item.TradebarcodeID + "',";
                    }
                    Codes = Codes.Substring(0, Codes.Length - 1);
                    OrderInfoBLL.myDataBase.Execute($"UPDATE WmsTradebarcode Set RState=2 where WmsTradebarcode.TradebarcodeID in ({Codes})");
                }
                else
                {
                    return Content(HttpStatusCode.InternalServerError, ErrorCode.WarehouseInfo01.GetMessage(Codes));
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        ///  库存条码拆包 去新留旧
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult CodeUnPack([FromBody] BasBarcodeInfo Info)
        {
            ResponseJson<BasBarcodeInfo> json = new ResponseJson<BasBarcodeInfo>()
            {
                Items = new List<BasBarcodeInfo>()
            };
            string Msg = string.Empty;
            try
            {
                BasBarcodeInfoBLL bas = new BasBarcodeInfoBLL();
                if (!bas.CodeUnPack(Info, ref json))
                {
                    return Content(HttpStatusCode.InternalServerError, ErrorCode.WarehouseInfo01.GetMessage(Info.BarcodeNO));
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        ///  获取基础条码对象
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetCodeInfo([FromBody] BasBarcodeInfo Info)
        {
            ResponseJson<BasBarcodeInfo> json = new ResponseJson<BasBarcodeInfo>()
            {
                Items = new List<BasBarcodeInfo>()
            };
            string Msg = string.Empty;
            try
            {
                BasBarcodeInfoBLL bas = new BasBarcodeInfoBLL();
                Sql sql = new Sql();
                sql.Append(bas.SqlSelect);
                sql.Where($"BasBarcodeInfo.BarcodeNO='{Info.BarcodeNO}'");
                var result = bas.myDataBase.FirstOrDefault<BasBarcodeInfo>(sql);
                if (result != null)
                {
                    json.Items.Add(result);
                    json.Message = "Success";
                }
                else
                {
                    json.Message = "Code Is not Exiten";
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        /// 整单捡料（算料+分页查询）
        /// </summary>
        /// <param name="Info"> 仓库交易单据对象(当CreateUser为空时只做查询不算料 )</param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult TradePickBarcode([FromBody] WmsTradeOrderInfo Info)
        {
            ResponseJson<WmsTradebarcode> json = new ResponseJson<WmsTradebarcode>();
            json.Items = new List<WmsTradebarcode>();
            string Msg = string.Empty;
            try
            {
                long Total = 0;
                List<WmsTradebarcode> barcodes = new List<WmsTradebarcode>();
                if (string.IsNullOrEmpty(Info.CreateUser))
                {
                    WmsProductionPickingOrderBLL.TradeOrderPickBarcode(Info.TradeOrderNO, out Msg, out barcodes, out Total, Info.PageIndex, Info.PageSize);
                }
                else
                {
                    WmsProductionPickingOrderBLL.TradeOrderPickBarcode(Info.TradeOrderNO,Info.CreateUser,out Msg,out barcodes, out Total, Info.PageIndex,Info.PageSize);
                }
               
                if (barcodes != null)
                {
                    json.Items= barcodes;
                    json.Message = "Success";
                }
                else
                {
                    json.Message = "Barcodes Is not Exiten";
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }

        /// <summary>
        /// 获取盘点类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetTakeType()
        {
            ResponseJson<TakeTypeInfo> json = new ResponseJson<TakeTypeInfo>();
            json.Items = new List<TakeTypeInfo>();
            string Msg = string.Empty;
            try
            {

                WmsStocktakeOrderInfoBLL bLL = new WmsStocktakeOrderInfoBLL();
                json.Items = bLL.GetTakeTypeList();
                if (!json.Items.Any())
                {
                    json.Code = 500;
                    return Content(HttpStatusCode.InternalServerError, "NO Data");
                }
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult GetStockTakeOrderList([FromBody] WmsStocktakeOrderInfo order)
        {
            ResponseJson<WmsStocktakeOrderInfo> json = new ResponseJson<WmsStocktakeOrderInfo>()
            {
                Code = 200,
                Message = string.Empty,
                Items = new List<WmsStocktakeOrderInfo>()
            };
            string Msg = string.Empty;
            long total = 0;
            try
            {
                //string obj= Regex.Unescape(JsonConvert.SerializeObject(Info));
                //WmsStocktakeOrderInfo order= JsonConvert.DeserializeObject<WmsStocktakeOrderInfo>(obj);

                WmsStocktakeOrderInfoBLL OrderInfoBLL = new WmsStocktakeOrderInfoBLL();
          
                List<WmsStocktakeOrderInfo> list = OrderInfoBLL.GetStockTakeOrderList(order, out total, out Msg);
                json.TotalPage = (int)total;
                json.Items = list;
                json.Message= Msg;
                return Ok(JsonConvert.SerializeObject(json));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
        }



        
    }
}